package com.book.bookshop.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.book.bookshop.entity.UserCartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import com.book.bookshop.entity.BsUser;
import com.book.bookshop.entity.Cart;
import com.book.bookshop.entity.CartVo;
import com.book.bookshop.mapper.CartMapper;
import com.book.bookshop.service.BookService;
import com.book.bookshop.service.CartService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
@RequestMapping("/cart")
public class CartController  {

    @Autowired
    private CartService cartService;


    @ResponseBody
    @RequestMapping("/add")
    public String addCart(Cart cart , HttpSession httpSession){
        BsUser user = (BsUser) httpSession.getAttribute("user");
        cart.setUserId(user.getId());
        //判断是否已经在购物车了
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());
        queryWrapper.eq("book_id",cart.getBookId());
        Cart queryCart = cartService.getOne(queryWrapper);
        if (queryCart == null){
            cartService.save(cart);

        }else {
            queryCart.setCount(queryCart.getCount()+cart.getCount());
            cartService.updateById(queryCart);
        }
        return "success";
    }

    /**
     * 查询当前的购物车
     * @param session
     * @return
     */

    @RequestMapping("/list")
    public String list(HttpSession session, Model model){
        BsUser user = (BsUser) session.getAttribute("user");
        List<CartVo> cartByUser = cartService.findCartByUser(user.getId());

        //将用户的购物车信息存放到session中
        UserCartVo userCartVo = cartService.wrapperCart(cartByUser);
        session.setAttribute("userCartInfo",userCartVo);//页面查不到会报错thymeleaf会报错
        model.addAttribute("cartList",cartByUser);
        return "cart";
    }

    @ResponseBody
    @RequestMapping("/update")
    public String update(HttpSession session,Cart cart){
        cartService.updateById(cart);
        BsUser user = (BsUser) session.getAttribute("user");
        System.out.println(user);
        List<CartVo> cartByUser = cartService.findCartByUser(user.getId());

        //将用户的购物车信息存放到session中
        UserCartVo userCartVo = cartService.wrapperCart(cartByUser);
        session.setAttribute("userCartInfo",userCartVo);//页面查不到会报错thymeleaf会报错
        double price = cartService.getCartItemTotal(cartByUser);
        return String.valueOf(price);
    }

    @ResponseBody
    @RequestMapping("/delete")
    public String delete(String ids){

        return cartService.batchDelete(ids);
    }
}
